<template>
	<div class="route-management">
		<el-button type="primary" class="uw-mb-10" @click="showAddDialog">Add Route</el-button>
		
		<el-table :data="routes" style="width: 100%" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" v-loading="loading">
			<el-table-column prop="id" label="路由标题" align="center">
				<template #default="{row}">
					<span>{{row.meta.title}}</span>
				</template>
			</el-table-column>
			<el-table-column prop="path" label="路由路径" align="center" />
			<el-table-column prop="name" label="路由名称" align="center" />
			<el-table-column prop="component" label="组件路径" align="center" />
			<el-table-column prop="redirect" label="重定向路由" align="center" />
			<el-table-column prop="sort" label="排序" width="80" align="center" />
			<el-table-column label="操作" width="180" align="center">
				<template #default="scope">
					<el-button type="primary" size="small" @click="showEditDialog(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="deleteRoute(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- Add/Edit Dialog -->
		<el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
			<el-form :model="form" label-width="100">
				<el-form-item label="父级路由" style="width: 90%;">
					<el-select v-model="form.parentId" placeholder="Select Parent Route">
						<el-option label="一级路由" :value="0"></el-option>
						<el-option v-for="route in routes" :key="route.id" :label="route.name" :value="route.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="路由路径" style="width: 90%;">
					<el-input v-model="form.path" placeholder="path"></el-input>
				</el-form-item>
				<el-form-item label="路由名称" style="width: 90%;">
					<el-input v-model="form.name" placeholder="name"></el-input>
				</el-form-item>
				<el-form-item label="组件路径" style="width: 90%;">
					<el-input v-model="form.component" placeholder="component"></el-input>
				</el-form-item>
				<el-form-item label="重定向路由" style="width: 90%;">
					<el-input v-model="form.redirect" placeholder="redirect"></el-input>
				</el-form-item>
				<el-form-item label="排序">
					<el-input-number v-model="form.sort"></el-input-number>
				</el-form-item>
				<!-- Meta Field (Key-Value Pairs) -->
				<el-form-item label="路由Meta" style="width: 90%;">
					<div v-for="(item, index) in form.meta" :key="index" style="margin-bottom: 10px;">
						<el-row :gutter="10">
							<el-col :span="10">
								<el-input v-model="item.key" placeholder="Meta Key"></el-input>
							</el-col>
							<el-col :span="10">
								<el-input v-model="item.value" placeholder="Meta Value"></el-input>
							</el-col>
							<el-col :span="4">
								<el-button type="danger" @click="removeMetaItem(index)">移除</el-button>
							</el-col>
						</el-row>
					</div>
					<el-button type="primary" @click="addMetaItem">新增Meta</el-button>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="dialogVisible = false">Cancel</el-button>
				<el-button type="primary" @click="handleSubmit">Confirm</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted } from 'vue';
	import { ElMessage } from 'element-plus';
	import { getRoutesListApi, addRoutesApi, editRoutesApi, deleteRoutesApi } from '@/api/route';

	// 页面状态
	const routes = ref([]);
	const loading = ref(false);
	const dialogVisible = ref(false);
	const dialogTitle = ref('');
	const form = reactive<any>({
		path: '',
		name: '',
		component: '',
		redirect: '',
		meta: [{ key: '', value: '' }],
		sort: 0,
		parentId: 0 
	});

	// 获取路由列表
	const fetchRoutes = async () => {
		loading.value = true;
		try {
			const res = await getRoutesListApi();
			routes.value = res.data 
		} catch (error) {
			ElMessage.error('Failed to fetch routes');
		} finally {
			loading.value = false;
		}
	};


	// 显示添加对话框
	const showAddDialog = () => {
		dialogTitle.value = '新增路由';
		Object.assign(form, { path: '', name: '', component: '', redirect: '', meta: [{ key: '', value: '' }], sort: 0, parentId: 0 });
		dialogVisible.value = true;
	};

	// 显示编辑对话框
	const showEditDialog = (route) => {
		dialogTitle.value = '编辑路由';
		// 解构并初始化 meta 为数组形式
		const metaArray = Object.entries(route.meta || {}).map(([key, value]) => ({ key, value }));
		
		Object.keys(form).forEach(key => {
		   form[key] = route[key];
		});
		form['meta'] = metaArray
		form['id'] = route['id']
		dialogVisible.value = true;
	};

	// 提交表单（添加/编辑）
	const handleSubmit = async () => {
		try {
			// 将 meta 数组转化为对象
			const metaObject = form.meta.reduce((acc, cur) => {
				if (cur.key) acc[cur.key] = cur.value;
				return acc;
			}, {});

			const routeData = { ...form, meta: metaObject };
			if (form.id) {
				await editRoutesApi(routeData);
				ElMessage.success('Route updated successfully');
			} else {
				await addRoutesApi(routeData);
				ElMessage.success('Route added successfully');
			}
			fetchRoutes();
			dialogVisible.value = false;
		} catch (error) {
			ElMessage.error('Operation failed');
		}
	};

	// 删除路由
	const deleteRoute = async (id) => {
		try {
			await deleteRoutesApi(id);
			ElMessage.success('Route deleted successfully');
			fetchRoutes();
		} catch (error) {
			ElMessage.error('Failed to delete route');
		}
	};

	// 增加和删除 meta 项
	const addMetaItem = () => {
		form.meta.push({ key: '', value: '' });
	};

	const removeMetaItem = (index:number) => {
		form.meta.splice(index, 1);
	};

	// 页面加载时获取路由数据
	onMounted(() => {
		fetchRoutes();
	});
</script>

<style scoped>
	
</style>